//
//  LoadAndSaveImage.m
//  CollectionTest
//
//  Created by A on 2020/11/7.
//  Copyright © 2020 TyTeam. All rights reserved.
//

#import "LoadAndSaveImage.h"

@interface LoadAndSaveImage ()
@property (nonatomic, strong) NSMutableDictionary *imgsDic;

@end

@implementation LoadAndSaveImage

static LoadAndSaveImage *manager = nil;

+ (LoadAndSaveImage *)shareManager {
    
    if (manager == nil) {
        manager = [[LoadAndSaveImage alloc] init];
        manager.imgsDic = [NSMutableDictionary dictionary];
    }
    
    return manager;
}


- (UIImage *)loadImageWithUrlString:(NSString *)urlString {
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filePath = [path stringByAppendingPathComponent:[urlString lastPathComponent]];
    
    if ([self.imgsDic valueForKey:urlString]) {
        //查找缓存
        NSData *imgData = [self.imgsDic valueForKey:urlString];
        
        UIImage *img = [UIImage imageWithData:imgData];
        
        return img;
    }
    else {
        //查找本地文件
        if ([NSData dataWithContentsOfFile:filePath]) {
            NSData *imgData = [NSData dataWithContentsOfFile:filePath];
            
            UIImage *img = [UIImage imageWithData:imgData];
            
            NSData *saveData = UIImagePNGRepresentation(img);
                    
            [self.imgsDic setValue:saveData forKey:urlString];
            
            return img;
        }else {
            //下载然后缓存
            NSURL *imgUrl = [NSURL URLWithString:urlString];
                    
            NSData *imgData = [[NSData alloc] initWithContentsOfURL:imgUrl];

            UIImage *img = [UIImage imageWithData:imgData];
                    
            NSData *saveData = UIImagePNGRepresentation(img);
                    
            [self.imgsDic setValue:saveData forKey:urlString];
                    
            BOOL sss = [saveData writeToFile:filePath atomically:YES];
              
            if (sss) {
                NSLog(@"yes");
            }
                    
            return img;
        }
        
    }
    
    
    
    return nil;
}




//- (void)removeAllCashe {
//
//    NSFileManager *fileManager = [NSFileManager defaultManager];
//    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
//
//    if ([fileManager fileExistsAtPath:path]) {
//        NSArray *childrenFiles = [fileManager subpathsAtPath:path];
//
//        for (NSString *fileName in childrenFiles) {
//
//            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
//
//            [fileManager removeItemAtPath:absolutePath error:nil];
//
//        }
//
//    }
//
//}

@end
